package com.example.springworkadmin.service;

import com.example.springworkadmin.dao.UserAccountDao;
import com.example.springworkadmin.entity.UserAccount;
import org.apache.ibatis.jdbc.Null;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class MyUserService implements UserDetailsService {
    @Autowired
    UserAccountDao userAccountDao;

    @Override
    public UserDetails loadUserByUsername(String s) throws UsernameNotFoundException {
        UserAccount userAccount=userAccountDao.getById(s);
        if(userAccount!= null){
            List<GrantedAuthority> authorities=AuthorityUtils.commaSeparatedStringToAuthorityList("ROLE_USER,USER");
            switch (userAccount.getAuthority()){
                case "ADMIN":
                    authorities = AuthorityUtils.commaSeparatedStringToAuthorityList("ROLE_ADMIN,ADMIN");
                    break;
                case "SUPER":
                    authorities = AuthorityUtils.commaSeparatedStringToAuthorityList("ROLE_ADMIN,ADMIN,SUPER");
            }
            User user=new User(s,"{noop}"+userAccount.getPassword(),authorities);
            return user;
        }else {
            throw  new UsernameNotFoundException("用户名不存在");
        }
    }
}
